package com.bwie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bwie.domain.Discount;
import com.bwie.mapper.DiscountMapper;
import com.bwie.utils.MobileMessageUtil;
import com.bwie.utils.R;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
import java.util.concurrent.TimeUnit;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.mapper.UserMapper;
import com.bwie.domain.User;
import com.bwie.service.UserService;

import javax.annotation.PostConstruct;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService{

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private DiscountMapper discountMapper;

    @Override
    public R send(User user) {
        if (user.getUserPhone()==null){
            return R.ERROR(500,"请先输入手机号");
        }
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<User>().eq(User::getUserPhone, user.getUserPhone());

        User one = userMapper.selectOne(wrapper);
        if (ObjectUtils.isEmpty(one)){
            return R.ERROR(500,"手机号不存在");
        }
        String s = redisTemplate.opsForValue().get(user.getUserPhone());
        if (!ObjectUtils.isEmpty(s)){
            return R.ERROR(500,"验证码5分钟只能发送一次");
        }
        String random = RandomStringUtils.randomNumeric(4);
        redisTemplate.opsForValue().set(user.getUserPhone(),random,5, TimeUnit.MINUTES);
        MobileMessageUtil.sendMobileMessage(user.getUserPhone(),random);
        return R.OK(random);
    }

    @Override
    public R login(User user) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<User>().eq(User::getUserPhone, user.getUserPhone());

        User one = userMapper.selectOne(wrapper);
        if (ObjectUtils.isEmpty(one)){
            return R.ERROR(500,"手机号不存在");
        }
        String s = redisTemplate.opsForValue().get(user.getUserPhone());
        if (!s.equals(user.getCode())){
            return R.ERROR(500,"验证码错误");
        }
        return R.OK();
    }

    @PostConstruct
    public void listAA(){
        List<Discount> discounts = discountMapper.selectList(null);
        redisTemplate.opsForValue().set("discounts", discounts.toString(),30,TimeUnit.MINUTES);
    }
}
